package copyengine.network.roomStructure.subMediator
{
	import copyengine.network.roomStructure.CENetworkCommandNotification;
	import copyengine.network.roomStructure.data.CENetworkRoomMediatorWhiteBoard;
	import copyengine.network.roomStructure.data.CENetworkRoomNeighbourInfoPackage;
	import copyengine.network.roomStructure.executeLayer.CENetworkRoomExecuteHandleNotification;
	import copyengine.utils.debug.CELog;

	import org.puremvc.as3.interfaces.INotification;

	public final class CENetworkRoomSubJoinLeaveMediator extends CENetworkRoomSubMediatorBasic
	{
		public function CENetworkRoomSubJoinLeaveMediator(_whiteBoard:CENetworkRoomMediatorWhiteBoard)
		{
			super(_whiteBoard);
		}

		override public function listNotificationInterests():Array
		{
			return [
				CENetworkRoomExecuteHandleNotification.SEND_RECEIVE_INCOMING_DATA,
				];
		}

		override public function handleNotification(notification:INotification):void
		{
			switch (notification.getName())
			{
				case CENetworkRoomExecuteHandleNotification.SEND_RECEIVE_INCOMING_DATA:
					onReceiveIncomingData(notification.getBody()["command"],
										  notification.getBody()["commandArg"],
										  notification.getBody()["forwardData"]);
					break;
			}
		}

		//====================
		//==Incoming Data
		//====================

		private function onReceiveIncomingData(_command:uint, _commandArg:Object, _forwardData:Object):void
		{
			switch (_command)
			{
				case CENetworkCommandNotification.S_RESERVE_COMMAND_SOME_ONE_JOIN_ROOM:
					onSomeOneJoinRoom(_commandArg);
					break;
				case CENetworkCommandNotification.S_RESERVE_COMMAND_SOME_ONE_LEAVE_ROOM:
					onSomeOneLeaveRoom(_commandArg);
					break;
				case CENetworkCommandNotification.S_RESERVE_COMMAND_CREATE_ROOM_RETURN:
					onCreateRoomCallBack(_commandArg);
					break;
				case CENetworkCommandNotification.S_RESERVE_COMMAND_JOIN_ROOM_RETURN:
					onJoinRoomCallBack(_commandArg);
					break;
			}
		}

		//==================
		//==Command Handle
		//==================

		private function onSomeOneLeaveRoom(_arg:Object):void
		{
			var leavePlayerInfoObj:Object = _arg["info"];
			var leavePlayerUID:String = leavePlayerInfoObj["uid"];

			var result:Boolean = deleteNeighbourInfoPackageByUID(leavePlayerUID);
			if (result)
			{
				var isRoomMasterChange:Boolean = false;
				if (whiteBoard.currentRoomMasterUID == leavePlayerUID)
				{
					isRoomMasterChange = true;
					whiteBoard.currentRoomMasterUID = getRoomMasterUID();

					//当前的玩家更换成房主,发送房主更改命令
					if (whiteBoard.playerUID == whiteBoard.currentRoomMasterUID)
					{
						var changeRoomMasterCommandArg:Object =
							{
								uid:whiteBoard.playerUID,
								roomID:whiteBoard.roomID
							};
						sendSocketCommand(CENetworkCommandNotification.F_RESERVE_COMMAND_CHANGE_MASTER, changeRoomMasterCommandArg);
					}
				}
				sendNeighbourChangeNotification(false, true, isRoomMasterChange, leavePlayerUID);
			}
			else
			{
				CELog.err("CENetworkRoomSubJoinLeaveMediator->onSomeOneLeaveRoom delete UID :" + leavePlayerUID + "not in vector");
			}

		}

		private function onSomeOneJoinRoom(_arg:Object):void
		{
			var newPlayerInfoObj:Object = _arg["info"];

			var neighbourInfo:CENetworkRoomNeighbourInfoPackage = new CENetworkRoomNeighbourInfoPackage();
			neighbourInfo.neighbourUID = newPlayerInfoObj["uid"];
			neighbourInfo.rankIndex = newPlayerInfoObj["index"];
			whiteBoard.roomNeighbourInfoPackageVector.push(neighbourInfo);

			//发送有人加入的Notification
			sendNeighbourChangeNotification(true, false, false, neighbourInfo.neighbourUID);
		}

		private function onCreateRoomCallBack(_arg:Object):void
		{
			//有可能没有创建成功
			if (_arg["errorCode"] == null)
			{
				//刚创建的房间,房间内无其他人员
				var neighbourInfo:CENetworkRoomNeighbourInfoPackage = new CENetworkRoomNeighbourInfoPackage();
				neighbourInfo.neighbourUID = whiteBoard.playerUID;
				neighbourInfo.rankIndex = 0;
				whiteBoard.roomNeighbourInfoPackageVector.push(neighbourInfo);

				//创建房间的人一定为房主
				whiteBoard.currentRoomMasterUID = whiteBoard.playerUID;

				sendNeighbourChangeNotification(false, false, false);
			}
		}

		private function onJoinRoomCallBack(_arg:Object):void
		{
			//有可能加入房间失败
			if (_arg["errorCode"] == null)
			{
				var roomInfoArray:Array = _arg["roomInfo"];
				//将房间内所有玩家的Info Push到Vector中
				for each (var roomInfoObj:Object in roomInfoArray)
				{
					var neighbourInfo:CENetworkRoomNeighbourInfoPackage = new CENetworkRoomNeighbourInfoPackage();
					neighbourInfo.neighbourUID = roomInfoObj["uid"];
					neighbourInfo.rankIndex = roomInfoObj["index"];
					whiteBoard.roomNeighbourInfoPackageVector.push(neighbourInfo);
				}
				//取得房主的UID
				whiteBoard.currentRoomMasterUID = getRoomMasterUID();

				//发送通知消息
				sendNeighbourChangeNotification(false, false, false);
			}
		}


		//================
		//==Common Function
		//================

		private function getRoomMasterUID():String
		{
			var minIndex:int = int.MAX_VALUE;
			var minUID:String = null;
			for each (var neighbourInfoPackage:CENetworkRoomNeighbourInfoPackage in whiteBoard.roomNeighbourInfoPackageVector)
			{
				if (neighbourInfoPackage.rankIndex < minIndex)
				{
					minIndex = neighbourInfoPackage.rankIndex;
					minUID = neighbourInfoPackage.neighbourUID;
				}
			}
			return minUID;
		}

		/**
		 *发送通知消息
		 */
		private function sendNeighbourChangeNotification(_isSomeOneJoin:Boolean,
														 _isSomeOneLeave:Boolean,
														 _isRoomMasterChange:Boolean,
														 _targetUID:String = null):void
		{
			sendNotification(CENetworkCommandNotification.SEND_DAEMON_HANDLE_ONLY_NEIGHBOUR_STATUS_CHANGE,
							 {
								 isSomeOneJoin:_isSomeOneJoin,
								 isSomeOneLeave:_isSomeOneLeave,
								 isRoomMasterChange:_isRoomMasterChange,
								 currentRoomMasterUID:whiteBoard.currentRoomMasterUID,
								 targetUID:_targetUID,
								 allNeighbourInfoPackageVector:whiteBoard.roomNeighbourInfoPackageVector
							 });
		}

		private function deleteNeighbourInfoPackageByUID(_uid:String):Boolean
		{
			for (var i:int = 0; i < whiteBoard.roomNeighbourInfoPackageVector.length; i++)
			{
				if (whiteBoard.roomNeighbourInfoPackageVector[i].neighbourUID == _uid)
				{
					whiteBoard.roomNeighbourInfoPackageVector.splice(i, 1);
					return true;
				}
			}
			return false;
		}

	}
}
